import time
from config import config
from pymongo import MongoClient

__all__ = ['ConnectMongo']


# MONGO_HOST = conf.get(mongo_name, 'host')
# MONGO_DB = conf.get(mongo_name, 'db')
# MONGO_USER = conf.get(mongo_name, 'user')
# MONGO_PASSWORD = conf.get(mongo_name, 'password')

class ConnectMongo(object):
    """调用pymongo一些模块，实现对数据库的操作"""

    def __init__(self, host=config.MONGO_HOST, username=config.MONGO_USER, password=config.MONGO_PASSWORD):
        self.client = MongoClient(host, username=username, password=password, maxpoolsize=2)

    # 测试链接
    def test_connection(self):
        return self.client

    # 插入数据
    @staticmethod
    def insert_data(collection=None, query=None, limit=None):
        # 记录第一次查询结果入库的时间
        insert_first_time = int(time.time() * 1000)
        query.update({
            'InsertTime': insert_first_time
        })
        collection.insert_one(query, limit)

    # 插入多条数据
    @staticmethod
    def insert_many_data(collection=None, query=None):
        collection.insert_many(query)

    # 查询数据
    @staticmethod
    def find_data(collection=None, query=None, limit=None):
        return list(collection.find(query, limit))

    # 查询N条数据
    @staticmethod
    def find_count_data(collection=None, query=None, limit=None, count=1):
        return list(collection.find(query, limit).limit(count))

    # 查询数据条数
    @staticmethod
    def find_size(collection=None, query=None, limit=None):
        return collection.find(query, limit).count()

    # 分页查询
    @staticmethod
    def page_find(collection=None, page_no=None, page_size=None, query=None, limit=None):
        skip = page_size * (page_no - 1)
        return list(collection.find(query, limit).limit(page_size).skip(skip))

    # 聚合查询
    @staticmethod
    def find_aggregate(collection=None, query=None):
        return list(collection.aggregate(query))

    # 更新单条数据
    @staticmethod
    def update_data(collection=None, query=None, data=None):
        collection.update_one(query, {'$set': data})

    # 更新多条数据
    @staticmethod
    def update_many_data(collection=None, query=None, data=None):
        collection.update_many(query, {'$set': data})

    # 多条数据更新插入
    @staticmethod
    def update_bulk_data(collection=None, update_list=None):
        bulk = collection.initialize_unordered_bulk_op()
        for update_data in update_list:
            bulk.find({'_id': update_data['_id']}).update({'$set': update_data})
        bulk.execute()

    # 删除单条数据
    @staticmethod
    def delete_data(collection=None, query=None):
        collection.delete_one(query)

    # 删除多条数据
    @staticmethod
    def delete_many_data(collection=None, query=None):
        collection.delete_many(query)
